package com.kingint.web.portal.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingint.mbg.bas.entity.BasItemsLeft;
import com.kingint.mbg.bas.mapper.BasItemsLeftMapper;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.web.portal.base.service.ItemsLeftService;
import com.kingint.web.sys.service.UmsAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ItemsLeftServiceImpl implements ItemsLeftService {
    @Resource
    private UmsAdminService adminService;
    @Resource
    private BasItemsLeftMapper itemsLeftMapper;

    @Override
    public List<BasItemsLeft> getAllItemsLeftList() {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if(StringUtils.isEmpty(hotelId)){
            log.debug("对应账号没有关联酒店id");
            return null;
        }
        QueryWrapper<BasItemsLeft> wrapper = new QueryWrapper<>();
        wrapper.eq("hotel_id",hotelId)
                .eq("status",0);
        List<BasItemsLeft> basItemsLefts = itemsLeftMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(basItemsLefts)){
            List<BasItemsLeft> collect = basItemsLefts.stream().filter(s -> s.getPid() == 0).collect(Collectors.toList());
            cancelRepairGoods(collect,basItemsLefts);
            return collect;
        }
        return null;
    }

    private void cancelRepairGoods(List<BasItemsLeft> aClass, List<BasItemsLeft> allList) {
        if (!CollectionUtils.isEmpty(aClass)) {
            //为一级菜单设置子菜单
            for (BasItemsLeft info : aClass) {
                getChildList(info, allList);
            }
        }
    }

    private void getChildList(BasItemsLeft info, List<BasItemsLeft> aClass) {
        List<BasItemsLeft> serviceClass = info.getItemsLeftList();
        if (CollectionUtils.isEmpty(serviceClass)) {
            serviceClass = new ArrayList<>();
        }
        for (BasItemsLeft ser : aClass) {
            if (ser.getPid() == info.getId()) {
                serviceClass.add(ser);
            }
        }
        //递归查询
        if (serviceClass.size() != 0) {
            for (BasItemsLeft child : serviceClass) {
                getChildList(child, aClass);
            }
        }
        info.setItemsLeftList(serviceClass);
    }
}
